package Aula21;


class KeyListNode{
    public int key;
    public KeyListNode next;
    
    public KeyListNode(int key, KeyListNode next){
    	this.key = key;
    	this.next = next;
    }
    
    public KeyListNode(int key){
    	this(key, null);
    }

	public KeyListNode() {
		super();
	}
	
	public KeyListNode copy(){
		KeyListNode node = this;
		KeyListNode newNode = new KeyListNode(node.key);
		KeyListNode atual = newNode;
		while(node.next != null){
			atual.next = new KeyListNode(node.next.key);
			atual = atual.next;
			node = node.next;
		}
		return newNode;
	}
	
	public void add(int chave){
		KeyListNode node = this;
		while(node.next != null && chave > node.next.key){
			node = node.next;
		}
		if(node == this && chave < node.key){
			int keyAtual = key;
			KeyListNode nextAtual = next; 
			key = chave;
			next = new KeyListNode(keyAtual, nextAtual);
		}else
			node.next = new KeyListNode(chave, node.next);
	}
	
	public int substituirChave(int newChave, int i) {
		KeyListNode node = getNode(i);
		if(node != null){
			int chave = node.key;
			node.key = newChave;
			return chave;
		}
		return -1;
	}
	
	public int get(int i){
		KeyListNode node = getNode(i);
		if(node != null)
			return node.key;
		return -1;
	}
	
	public int indexOf(int chave){
		KeyListNode node = this;
		int i = 0;
		for(; node != null && node.key != chave; i++){
			node = node.next;
		}
		if(node == null)
			return -1;
		return i;
	}
	
	public KeyListNode getNode(int i){
		KeyListNode node = this;
		for(; i > 0; i--){
			node = node.next;
			if(node == null)
				return null;
		}
		return node;
	}
	
	public int remove(int chave){
		KeyListNode anterior = null;
		KeyListNode atual = this;

		while (atual != null && atual.key != chave) {
			anterior = atual;
			atual = atual.next;
		}
		if(atual == null){
			return -1;
		}
		if(anterior == null){
			if(atual.next == null)
				System.out.println("Erro em keyList");
			this.key = atual.next.key;			
			atual.next = atual.next.next;
		}else
			anterior.next = atual.next;
		return chave;		
	}
	
	public int last(){
		return lastNode().key;
	}
	
	public KeyListNode lastNode(){
		KeyListNode atual = this;
		while (atual.next != null) {
			atual = atual.next;
		}
		return atual;
	}
	
	@Override
	public String toString() {
		String str = "[" + key;
		KeyListNode node = next;
		while(node != null){
			str += ", " + node.key;
			node = node.next;
		}
		str += "]";
		return str; 
	}
	
}
